<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>客户资料管理</template>
      <template #extra>
        <a-button type="primary" @click="openCreateModal">
          <template #icon><icon-plus /></template>
          新增客户
        </a-button>
      </template>
      
      <!-- 搜索区域 -->
      <a-form :model="searchForm" class="search-form" layout="inline">
        <a-form-item field="keyword" label="关键字">
          <a-input v-model="searchForm.keyword" placeholder="客户名称/编码" allow-clear />
        </a-form-item>
        <a-form-item field="level" label="客户等级">
          <a-select v-model="searchForm.level" placeholder="全部等级" allow-clear>
            <a-option v-for="level in customerLevels" :key="level.value" :value="level.value">{{ level.label }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="status" label="状态">
          <a-select v-model="searchForm.status" placeholder="全部状态" allow-clear>
            <a-option value="1">正常</a-option>
            <a-option value="0">禁用</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="search">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="reset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 表格区域 -->
      <a-table 
        :data="customerList" 
        :loading="loading" 
        :pagination="pagination"
        @page-change="onPageChange"
        :bordered="false"
        stripe
      >
        <template #columns>
          <a-table-column title="客户编码" data-index="code" :width="120" />
          <a-table-column title="客户名称" data-index="name" :width="200" />
          <a-table-column title="联系人" data-index="contactPerson" :width="100" />
          <a-table-column title="联系电话" data-index="contactPhone" :width="140" />
          <a-table-column title="客户等级" :width="120">
            <template #cell="{ record }">
              <a-tag :color="getLevelColor(record.level)">{{ getLevelLabel(record.level) }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="账期(天)" data-index="paymentDays" :width="100" />
          <a-table-column title="合作状态" :width="100">
            <template #cell="{ record }">
              <a-tag :color="record.status === 1 ? 'green' : 'red'">
                {{ record.status === 1 ? '正常' : '禁用' }}
              </a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createTime" :width="180" />
          <a-table-column title="操作" fixed="right" :width="200">
            <template #cell="{ record }">
              <a-space>
                <a-button type="text" size="small" @click="openEditModal(record)">
                  编辑
                </a-button>
                <a-divider direction="vertical" />
                <a-button type="text" size="small" @click="openDetailModal(record)">
                  查看
                </a-button>
                <a-divider direction="vertical" />
                <a-popconfirm
                  content="确定要删除这个客户吗？"
                  @ok="handleDelete(record)"
                >
                  <a-button type="text" status="danger" size="small">
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑客户弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalType === 'create' ? '新增客户' : '编辑客户'"
      @ok="handleSubmit"
      @cancel="handleModalCancel"
      :ok-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="vertical"
      >
        <a-form-item field="name" label="客户名称" required>
          <a-input v-model="form.name" placeholder="请输入客户名称" allow-clear />
        </a-form-item>
        <a-form-item field="code" label="客户编码" required>
          <a-input v-model="form.code" placeholder="请输入客户编码" allow-clear />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="level" label="客户等级" required>
              <a-select v-model="form.level" placeholder="请选择客户等级">
                <a-option v-for="level in customerLevels" :key="level.value" :value="level.value">{{ level.label }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="paymentDays" label="账期(天)">
              <a-input-number v-model="form.paymentDays" placeholder="请输入账期天数" :min="0" :max="90" style="width: 100%;" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="contactPerson" label="联系人" required>
              <a-input v-model="form.contactPerson" placeholder="请输入联系人姓名" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="contactPhone" label="联系电话" required>
              <a-input v-model="form.contactPhone" placeholder="请输入联系电话" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="email" label="电子邮箱">
          <a-input v-model="form.email" placeholder="请输入电子邮箱" allow-clear />
        </a-form-item>
        <a-form-item field="address" label="送货地址">
          <a-textarea v-model="form.address" placeholder="请输入送货地址" allow-clear />
        </a-form-item>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="creditCode" label="统一社会信用代码">
              <a-input v-model="form.creditCode" placeholder="请输入统一社会信用代码" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="taxNumber" label="税号">
              <a-input v-model="form.taxNumber" placeholder="请输入税号" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item field="remark" label="备注信息">
          <a-textarea v-model="form.remark" placeholder="请输入备注信息" allow-clear />
        </a-form-item>
        <a-form-item field="status" label="状态" required>
          <a-radio-group v-model="form.status" type="button">
            <a-radio :value="1">正常</a-radio>
            <a-radio :value="0">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 客户详情弹窗 -->
    <a-modal
      v-model:visible="detailVisible"
      title="客户详情"
      @cancel="detailVisible = false"
      :footer="false"
    >
      <a-descriptions
        :data="detailData"
        :column="1"
        layout="horizontal"
        bordered
      >
        <template #label="{label}">
          <div style="width: 120px;">{{ label }}</div>
        </template>
        <template #value="{value}">
          <div>{{ value }}</div>
        </template>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { IconPlus, IconSearch, IconRefresh } from '@arco-design/web-vue/es/icon';
import { useCustomerStore } from '@/stores/customer';

// 客户等级选项
const customerLevels = [
  { value: 1, label: '普通客户', color: 'blue' },
  { value: 2, label: 'VIP客户', color: 'orange' },
  { value: 3, label: '重要客户', color: 'red' },
];

// 使用客户Store
const customerStore = useCustomerStore();

// 表单相关的状态
const formRef = ref(null);
const form = reactive({
  id: '',
  name: '',
  code: '',
  level: 1,
  paymentDays: 30,
  contactPerson: '',
  contactPhone: '',
  email: '',
  address: '',
  creditCode: '',
  taxNumber: '',
  remark: '',
  status: 1
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入客户名称' }],
  code: [{ required: true, message: '请输入客户编码' }],
  level: [{ required: true, message: '请选择客户等级' }],
  contactPerson: [{ required: true, message: '请输入联系人姓名' }],
  contactPhone: [{ required: true, message: '请输入联系电话' }],
  status: [{ required: true, message: '请选择状态' }]
};

// 搜索表单
const searchForm = reactive({
  keyword: '',
  level: undefined,
  status: undefined
});

// 模态框状态
const modalVisible = ref(false);
const modalType = ref('create'); // 'create' 或 'edit'
const submitLoading = ref(false);
const detailVisible = ref(false);
const detailData = ref([]);

// 表格相关状态
const loading = ref(false);
const customerList = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true
});

// 获取客户列表
const fetchCustomerList = async () => {
  loading.value = true;
  try {
    // 使用真实API获取数据
    const result = await customerStore.getCustomerList({
      page: pagination.current,
      page_size: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status ? parseInt(searchForm.status) : undefined,
      level: searchForm.level ? parseInt(searchForm.level) : undefined
    }, true, true); // 显示加载状态和成功消息
    
    if (result.success) {
      // 更新分页信息
      pagination.current = result.data.pagination.current;
      pagination.pageSize = result.data.pagination.pageSize;
      pagination.total = result.data.pagination.total;
      
      // 更新客户列表
      customerList.value = result.data.list.map(item => ({
        id: item.id,
        code: item.code,
        name: item.name,
        contactPerson: item.contact,
        contactPhone: item.phone,
        email: item.email,
        address: item.address,
        level: item.level,
        paymentDays: 30, // 默认值，API中若有则使用API值
        creditCode: '',
        taxNumber: item.tax_number || '',
        remark: item.remark,
        status: item.status,
        createTime: new Date(item.created_at).toLocaleString()
      }));
    }
  } catch (error) {
    console.error('获取客户列表出错:', error);
    Message.error('系统错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 搜索操作
const search = () => {
  pagination.current = 1;
  fetchCustomerList();
};

// 重置搜索条件
const reset = () => {
  searchForm.keyword = '';
  searchForm.level = undefined;
  searchForm.status = undefined;
  pagination.current = 1;
  fetchCustomerList();
};

// 分页变化
const onPageChange = (page) => {
  pagination.current = page;
  fetchCustomerList();
};

// 获取等级文本和颜色
const getLevelLabel = (level) => {
  const found = customerLevels.find(item => item.value === level);
  return found ? found.label : '未知';
};

const getLevelColor = (level) => {
  const found = customerLevels.find(item => item.value === level);
  return found ? found.color : '';
};

// 打开新增模态框
const openCreateModal = () => {
  modalType.value = 'create';
  resetForm();
  modalVisible.value = true;
};

// 打开编辑模态框
const openEditModal = (record) => {
  modalType.value = 'edit';
  Object.keys(form).forEach(key => {
    if (key in record) {
      form[key] = record[key];
    }
  });
  modalVisible.value = true;
};

// 打开详情模态框
const openDetailModal = async (record) => {
  try {
    // 使用模拟API获取客户详情
    const response = await mockCustomerApi.getCustomerDetail(record.id);
    
    if (response.code === 0) {
      const customer = response.data;
      // 转换为描述列表格式
      detailData.value = [
        { label: '客户名称', value: customer.name },
        { label: '客户编码', value: customer.code },
        { label: '客户等级', value: getLevelLabel(customer.type) },
        { label: '联系人', value: customer.contact },
        { label: '联系电话', value: customer.phone },
        { label: '电子邮箱', value: customer.email },
        { label: '送货地址', value: customer.address },
        { label: '账期(天)', value: customer.payment_term },
        { label: '信用额度', value: `¥${customer.credit_limit.toLocaleString()}` },
        { label: '统一社会信用代码', value: '' },
        { label: '税号', value: '' },
        { label: '备注信息', value: customer.remark || '无' },
        { label: '状态', value: customer.status === 1 ? '正常' : '禁用' },
        { label: '创建时间', value: customer.created_at },
        { label: '最后更新', value: customer.updated_at },
        { label: '创建人', value: customer.creator || '系统管理员' },
        { label: '更新人', value: customer.updater || '系统管理员' }
      ];
      detailVisible.value = true;
    } else {
      Message.error('获取客户详情失败');
    }
  } catch (error) {
    console.error('获取客户详情出错:', error);
    Message.error('系统错误，请稍后重试');
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(form).forEach(key => {
    if (key === 'level') {
      form[key] = 1;
    } else if (key === 'status') {
      form[key] = 1;
    } else if (key === 'paymentDays') {
      form[key] = 30;
    } else {
      form[key] = '';
    }
  });
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    // 表单验证
    await formRef.value.validate();
    submitLoading.value = true;
    
    // 准备提交的数据
    const submitData = {
      name: form.name,
      code: form.code,
      type: form.level,
      contact: form.contactPerson,
      phone: form.contactPhone,
      email: form.email,
      address: form.address,
      status: form.status,
      payment_term: form.paymentDays,
      remark: form.remark
    };
    
    let response;
    if (modalType.value === 'create') {
      // 使用模拟API创建客户
      response = await mockCustomerApi.createCustomer(submitData);
    } else {
      // 使用模拟API更新客户
      response = await mockCustomerApi.updateCustomer(form.id, submitData);
    }
    
    if (response.code === 0) {
      Message.success(modalType.value === 'create' ? '创建客户成功' : '更新客户成功');
      modalVisible.value = false;
      fetchCustomerList(); // 刷新列表
    } else {
      Message.error(response.message || '操作失败');
    }
  } catch (error) {
    console.error('表单提交出错:', error);
    Message.error('提交失败，请检查表单填写是否正确');
  } finally {
    submitLoading.value = false;
  }
};

// 取消模态框
const handleModalCancel = () => {
  modalVisible.value = false;
  resetForm();
};

// 删除客户
const handleDelete = async (record) => {
  try {
    loading.value = true;
    // 使用模拟API删除客户
    const response = await mockCustomerApi.deleteCustomer(record.id);
    
    if (response.code === 0) {
      Message.success('删除客户成功');
      // 如果当前页只有一条数据，且不是第一页，则返回上一页
      if (customerList.value.length === 1 && pagination.current > 1) {
        pagination.current -= 1;
      }
      fetchCustomerList(); // 刷新列表
    } else {
      Message.error(response.message || '删除失败');
    }
  } catch (error) {
    console.error('删除客户出错:', error);
    Message.error('系统错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取客户列表
onMounted(() => {
  fetchCustomerList();
});
</script>

<style lang="less" scoped>
@import '@/styles/variables.less';

.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  margin-top: 16px;
  margin-bottom: 20px;
  
  :deep(.arco-card-header) {
    height: 52px;
    padding: 16px 20px;
    border-bottom: 1px solid var(--color-border);
  }
}

.search-form {
  margin-bottom: 8px;
}

:deep(.arco-modal-footer .arco-btn),
:deep(.modal-footer .arco-btn) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
</style> 